#include <nmea/nmea.h>

#include <string.h>
#include <stdio.h>

#ifdef NMEA_WIN
#   include <io.h>
#endif

void trace(const char *str, int str_size)
{
    printf("Trace: ");
    write(1, str, str_size);
    printf("\n");
}
void error(const char *str, int str_size)
{
    printf("Error: ");
    write(1, str, str_size);
    printf("\n");
}

void print_nmeaINFO(const nmeaINFO* info)
{
  int ix = 0;
  const nmeaSATELLITE *sat;
  char datetime[512];
  sprintf(datetime, "%04d-%02d-%02d %02d:%02d:%02d.%d", info->utc.year, info->utc.mon, info->utc.day,
    info->utc.hour, info->utc.min, info->utc.sec, info->utc.hsec);

  printf("%-32s = %08x\n", "smask", info->smask);
  printf("%-32s = %s\n", "utc", datetime);
  printf("%-32s = %d %s\n", "sig", info->sig, info->sig ? "" : "Invalid");
  printf("%-32s = %d\n", "fix", info->fix);
  printf("%-32s = %f\n", "PDOP", info->PDOP);
  printf("%-32s = %f\n", "HDOP", info->HDOP);
  printf("%-32s = %f\n", "VDOP", info->VDOP);
  printf("%-32s = %f\n", "lat", info->lat);
  printf("%-32s = %f\n", "lon", info->lon);
  printf("%-32s = %f\n", "elv", info->elv);
  printf("%-32s = %f\n", "speed", info->speed);
  printf("%-32s = %f\n", "direction", info->direction);
  printf("%-32s = %f\n", "declination", info->declination);

  printf("***********************************************************\n");
  if (info->satinfo.inview) {
    printf("%-32s = %d\n", "satinfo.inuse", info->satinfo.inuse);
    printf("%-32s = %d\n", "satinfo.inview", info->satinfo.inview);
    sat = info->satinfo.sat;
    for (; ix != NMEA_MAXSAT; ++ix) {
      printf("==============================%d===============================\n", ix + 1);
      printf("%-32s = %d\n", "satinfo.sat.id", sat[ix].id);
      printf("%-32s = %d\n", "satinfo.sat.in_use", sat[ix].in_use);
      printf("%-32s = %d\n", "satinfo.sat.elv", sat[ix].elv);
      printf("%-32s = %d\n", "satinfo.sat.azimuth", sat[ix].azimuth);
      printf("%-32s = %d\n", "satinfo.sat.sig", sat[ix].sig);
    }
  }
}

int main()
{
    nmeaINFO info;
    nmeaPARSER parser;
    FILE *file;
    char buff[2048];
    int size, it = 0;
    nmeaPOS dpos;

    file = fopen("gpslog.txt", "rb");

    if(!file)
        return -1;

    nmea_property()->trace_func = &trace;
    nmea_property()->error_func = &error;

    nmea_zero_INFO(&info);
    nmea_parser_init(&parser);

    /*
    while(1)
    {
    */

    while(!feof(file))
    {
        size = (int)fread(&buff[0], 1, 100, file);

        nmea_parse(&parser, &buff[0], size, &info);

        printf("###########################################\n");
        print_nmeaINFO(&info);
        nmea_info2pos(&info, &dpos);

        printf(
            "%03d, Lat: %f, Lon: %f, Sig: %d, Fix: %d\n",
            it++, dpos.lat, dpos.lon, info.sig, info.fix
            );
    }

    fseek(file, 0, SEEK_SET);

    /*
    }
    */

    nmea_parser_destroy(&parser);
    fclose(file);

    getchar();
    return 0;
}
